import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from "@angular/forms";
import {ConfirmationService, SelectItem} from "primeng/primeng";
import {ReportsService} from "../reports.service";
import {FileUploader} from "ng2-file-upload";
import {environment} from "../../../environments/environment";

@Component({
  selector: 'app-templet-edit',
  templateUrl: './templet-edit.component.html',
  styleUrls: ['./templet-edit.component.css']
})
export class TempletEditComponent implements OnInit {
  display;
  title;
  templet: FormGroup;
  types: SelectItem[];
  ways: SelectItem[];
  sheets: SelectItem[];
  weeks: SelectItem[];
  type;
  way;
  sheet;
  week;
  sid;
  name;
  url;
  url_name;
  dayTime;
  weekTime;
  monthTime;
  yearTime;
  @Output() closeTempletEdit =new EventEmitter();
  @Output() addTem = new EventEmitter(); //新增人员
  @Output() updateTem = new EventEmitter(); //修改人员
  @Input() currentTem;
  @Input() state;
  ch;
  dateShow: boolean = false;
  dayShow: boolean = false;
  weekShow: boolean = false;
  monthShow: boolean = false;
  yearShow: boolean = false;
  uploader: FileUploader;
  hasBaseDropZoneOver: boolean = false;
  hasAnotherDropZoneOver: boolean = false;
  dataSource;
  totalRecords: number;
  assets;
  submitAddTemp = {//新增模板参数
    "name": "",
    "type": "",
    "way": "",
    "auto_build_time": "",
    "auto_week_build_time": "",
    "sheet": "",
    "url": ""
  };
  submitModTemp = {//修改模板参数
    "sid": "",
    "name": "",
    "type": "",
    "way": "",
    "auto_build_time": "",
    "auto_week_build_time": "",
    "sheet": "",
    "url": ""
  };

  constructor(
    private fb: FormBuilder,
    private reportsService: ReportsService,
    private confirmationService: ConfirmationService,
    ) {
    this.templet = fb.group({
      name: ["", Validators.required],
      url: ["", Validators.required],
      url_name: ["", Validators.required],
      type: ["", Validators.required],
      way: ["", Validators.required],
      dayTime: [""],
      monthTime: [""],
      yearTime: [""],
      week: [""],
      weekTime: [""],
      sheet: ["", Validators.required],
    })
  }

  ngOnInit() {
    // console.log(this.currentTem)
    this.display = true;
    if(this.state == "add"){
      this.initPageParam("新增模板","","","","day","manual","","monitor");
    }else {
      this.sid = this.currentTem.sid;
      let urlName = this.currentTem.url.substring(this.currentTem.url.lastIndexOf("/") + 1);
      // this.currentTem.auto_build_time = "08";
      this.initPageParam("修改模板",this.currentTem.name,urlName,this.currentTem.url,this.currentTem.type,this.currentTem.way,this.currentTem.auto_build_time || this.currentTem.auto_week_build_time,this.currentTem.sheet);
    }
    this.showWhichDate();
    this.types = [
      {label:"日报", value: "day"},
      {label:"周报", value: "week"},
      {label:"月报", value: "month"},
      {label:"年报", value: "year"},
      {label:"其他", value: "ohers"},
    ];
    this.ways = [
      {label:"手动", value: "manual"},
      {label:"自动", value: "auto"},
    ];
    this.sheets = [
      {label:"温湿度模板", value: "Monitor"},
      {label:"报障模板", value: "Fault"},
      {label:"巡检模板", value: "Inspection"},
      {label:"资产模板", value: "Asset"},
      {label:"能效模板", value: "Efficiency"},
      {label:"容量模板", value: "Capacity"},
    ];
    this.weeks = [
      {label:"周一", value: "Mon"},
      {label:"周二", value: "Tues"},
      {label:"周三", value: "Wed"},
      {label:"周四", value: "Thurs"},
      {label:"周五", value: "Fri"},
      {label:"周六", value: "Sat"},
      {label:"周日", value: "Sun"},
    ];
    this.ch = {
      firstDayOfWeek: 0,
      dayNames: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"],
      dayNamesShort: ["周日", "周一", "周二", "周三", "周四", "周五", "周六"],
      dayNamesMin: ["日", "一", "二", "三", "四", "五", "六"],
      monthNames: ["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"],
      monthNamesShort: ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"]
    };
    this.uploader = new FileUploader({url: `${environment.url.management}/reports/upload`})
    this.uploader.onCompleteItem = (item: any, response:any, status:any, headers:any) => {
      console.log("上传成功！")
      console.log(response);
      if(response.search("{")===-1) {
        this.confirmationService.confirm({
          message: '请导入excel文件',
          rejectVisible:false,
        })
        return
      }
      let body = JSON.parse(response);
      if(body.errcode==='00000'){
        this.confirmationService.confirm({
          message: '导入数据成功！',
          rejectVisible:false,
        })
      }else{
        this.confirmationService.confirm({
          message:body['errmsg'],
          rejectVisible:false
        })
        return
      }
      this.url = body.datas[0].path;
      console.log(this.url);
      this.dataSource = body.datas;
      if(this.dataSource){
        this.totalRecords = this.dataSource.length;
        this.assets = this.dataSource.slice(0,10);
      }else{
        this.totalRecords = 0;
        this.assets = []
      }
    }
  }

  selectedFileOnChanged(event: any) {
    this.url_name = event.target.value.substring(12);
  }

  public fileOverBase(e:any):void {
    console.log(e)
    this.hasBaseDropZoneOver = e;
  }

  public fileOverAnother(e:any):void {
    console.log(e)
    this.hasAnotherDropZoneOver = e;
  }

  //清空，文件上传
  clearFile(){
    this.url_name = "";
    this.url = "";
  }

  initPageParam(title,name,url_name,url,type,way,autotime,sheet){
    this.title = title;
    this.name = name;
    this.url_name = url_name;
    this.url = url;
    this.type = type;
    this.way = way;
    this.sheet = sheet;
    if (way == "auto"){
      if(type == "day"){
        this.dayTime = autotime;
      }else if(type == "week"){
        this.week = autotime.split(" ")[0];
        this.weekTime = autotime.split(" ")[1];
      }else if(type == "month"){
        this.monthTime = new Date(new Date().getFullYear() + "-" + (new Date().getMonth() + 1) + "-" + autotime);
      }else if(type == "year"){
        this.yearTime = autotime;
      }else{

      }
    }
  }

  //判断显示哪个日期选择器
  showWhichDate(){
    if(this.way == "auto" && this.type == "week"){//周报
      this.dateShow = true;
      this.weekShow = true;
      this.dayShow = false;
      this.monthShow = false;
      this.yearShow = false;
    }else if(this.way == "auto"){
      this.dateShow = true;
      if(this.type == "day"){//日报
        this.dayShow = true;
        this.weekShow = false;
        this.monthShow = false;
        this.yearShow = false;
      }else if(this.type == "month"){//月报
        this.monthShow = true;
        this.weekShow = false;
        this.dayShow = false;
        this.yearShow = false;
      }else if(this.type == "year"){//年报
        this.yearShow = true;
        this.weekShow = false;
        this.dayShow = false;
        this.monthShow = false;
      }else {//其他

      }
    }else {
      this.dateShow = false;
    }
  }

  //确定
  formSubmit(bool){
    if(this.state ==='add'){
      this.submitAddTemp.name = this.templet.value.name;
      this.submitAddTemp.type = this.templet.value.type;
      this.submitAddTemp.way = this.templet.value.way;
      this.submitAddTemp.sheet = this.templet.value.sheet;
      // this.submitAddTemp.url = this.templet.value.url;
      this.submitAddTemp.url = this.url;
      if(this.way == "auto"){
        if (this.type == "day"){
          this.submitAddTemp.auto_build_time = this.templet.value.dayTime;
          this.submitAddTemp.auto_week_build_time = "";
        }else if(this.type == "week"){
          this.submitAddTemp.auto_week_build_time = this.templet.value.week + " " + this.templet.value.weekTime;
          this.submitAddTemp.auto_build_time = "";
        }else if(this.type == "month"){
          this.submitAddTemp.auto_build_time = this.templet.value.monthTime;
          this.submitAddTemp.auto_week_build_time = "";
        }else if(this.type == "year"){
          this.submitAddTemp.auto_build_time = this.templet.value.yearTime;
          this.submitAddTemp.auto_week_build_time = "";
        }
      }else {
        this.submitAddTemp.auto_build_time = '';
        this.submitAddTemp.auto_week_build_time = '';
      }
      console.log(this.submitAddTemp)
      this.addTemplet(bool);
    }else{
      this.submitModTemp.sid = this.sid;
      this.submitModTemp.name = this.templet.value.name;
      this.submitModTemp.type = this.templet.value.type;
      this.submitModTemp.way = this.templet.value.way;
      this.submitModTemp.sheet = this.templet.value.sheet;
      // this.submitModTemp.url = this.templet.value.url;
      this.submitModTemp.url = this.url;
      if(this.way == "auto"){
        if (this.type == "day"){
          this.submitModTemp.auto_build_time = this.templet.value.dayTime;
          this.submitModTemp.auto_week_build_time = "";
        }else if(this.type == "week"){
          this.submitModTemp.auto_week_build_time = this.templet.value.week + " " + this.templet.value.weekTime;
          this.submitModTemp.auto_build_time = "";
        }else if(this.type == "month"){
          this.submitModTemp.auto_build_time = this.templet.value.monthTime;
          this.submitModTemp.auto_week_build_time = "";
        }else if(this.type == "year"){
          this.submitModTemp.auto_build_time = this.templet.value.yearTime;
          this.submitModTemp.auto_week_build_time = "";
        }
      }else {
        this.submitModTemp.auto_build_time = '';
        this.submitModTemp.auto_week_build_time = '';
      }
      console.log(this.submitModTemp)
      this.updateTemplet(bool);
    }
  }

  //新增模板
  addTemplet(bool){
    this.reportsService.addTemplet(this.submitAddTemp).subscribe(()=>{
      this.addTem.emit(bool);
    },(err:Error)=>{
      let message ;
      if(JSON.parse(JSON.stringify(err)).status===504){
        message = '似乎网络出现了问题，稍后重试'
      }else{
        message =err
      }
      this.confirmationService.confirm({
        message: message,
        rejectVisible:false,
      })
    })
  }

  //修改模板
  updateTemplet(bool){
    console.log(this.submitModTemp);
    this.reportsService.updateTemplet(this.submitModTemp).subscribe(()=>{
      this.updateTem.emit(this.currentTem);
      this.closeTempletEdit.emit(bool);
    })
  }

  closeTemEditMask(bool){
    this.closeTempletEdit.emit(bool);
  }

}
